package xh.server.processors;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpResponse;
import xh.server.PlayerStatusRequestManager;
import xh.server.ServerController;
import xh.util.HttpUtils;

/**
 * Created by Administrator on 2016/6/30.
 */
public class LongPollingProcessor extends AbstractProcessor {

    ChannelHandlerContext ctx;
    String uri;

    public LongPollingProcessor(ChannelHandlerContext ctx, String uri) {
        this.ctx = ctx;
        this.uri = uri;
    }

    public FullHttpResponse process() {

        String[] parts = uri.split("/");
        if (parts == null || parts.length == 0) {
            return HttpUtils._404();
        }

        if (parts[0].equals("playerStatus")) {
            if (parts.length != 2) {
                return HttpUtils._404();
            }

            long lastUpTime = Long.parseLong(parts[1]);

            PlayerStatusRequestManager prm = ServerController.playerStatusRequestHolder();

            if (prm.hasUpdate(lastUpTime)) {
                prm.doResponse(ctx.channel());
            } else {
                prm.holdRequest(ctx.channel(), System.currentTimeMillis(), 30 * 1000l);
            }
        }
        return null;
    }
}
